package com.zsy._13并发包_ForkJoin;

import java.util.concurrent.RecursiveTask;

/**
 * @author: zhangshuaiyin
 * @date: 2021/8/25 20:11
 */
public class ForkJoinTaskDemo extends RecursiveTask<Long> {

    /**
     * 临界值，大于该值时拆分任务
     */
    private final static Long temp = 10000L;

    private final Long start;

    private final Long end;

    public ForkJoinTaskDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if (end - start < temp) {
            System.out.println("开始计算的部分：startValue = " + start + ";endValue = " + end);
            long sum = 0L;
            for (long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        }

        long middle = (start + end) / 2; // 中间值
        ForkJoinTaskDemo task1 = new ForkJoinTaskDemo(start, middle);
        task1.fork(); // 拆分任务，把任务压入线程队列
        ForkJoinTaskDemo task2 = new ForkJoinTaskDemo(middle+1, end);
        task2.fork(); // 拆分任务，把任务压入线程队列
        // 汇总拆分任务的计算结果
        return task1.join() + task2.join();
    }
}
